<template>
    <!-- 省份选择 -->
    <a-tree-select
      style="width: 180px"
      :treeData="provinceData"
      :value="province"
      placeholder="请选择省份"
      allowClear
      @change="onProvinceChange"
    />

    <!-- 城市选择 -->
    <a-tree-select
      style="width: 180px"
      :treeData="cityData"
      :value="city"
      placeholder="请选择城市"
      allowClear
      :disabled="!province"
      @change="onCityChange"
    />
</template>

<script setup lang="ts">
import { ref, watch, onMounted } from 'vue'

// props：父组件可以通过 v-model 拿到省、市
const props = defineProps({
  modelValue: { type: Object, default: () => ({ province: '', city: '' }) },
  getProvinces: { type: Function as PropType<() => Promise<any[]>>, required: true },
  getCities: { type: Function as PropType<(province: string) => Promise<any[]>>, required: true }
})
const emit = defineEmits(['update:modelValue'])

// 内部值
const province = ref(props.modelValue.province || '')
const city = ref(props.modelValue.city || '')

// 数据源
const provinceData = ref<any[]>([])
const cityData = ref<any[]>([])

// 初始化加载省份
onMounted(async () => {
  provinceData.value = await props.getProvinces()
  if (province.value) {
    cityData.value = await props.getCities(province.value)
  }
})

// 省份变化
async function onProvinceChange(value: string) {
  province.value = value
  city.value = '' // 清空城市
  cityData.value = value ? await props.getCities(value) : []
  emit('update:modelValue', { province: province.value, city: city.value })
}

// 城市变化
function onCityChange(value: string) {
  city.value = value
  emit('update:modelValue', { province: province.value, city: city.value })
}

// 父组件 v-model 同步
watch(
  () => props.modelValue,
  (val) => {
    province.value = val.province
    city.value = val.city
  },
  { deep: true }
)
</script>
